<template>
  <div>
    <Header :title="'返回'" :subTitle="'中奖记录'" :hasBackPath="true" @headerBack="$router.back()"></Header>
    <a-card :bordered="false">
      <!-- <h3>中奖记录</h3> -->
      <MemberPromotionsFilter ref="filter" :type="2" @onImportLogistics="onImportLogistics" @onExport="onExport" @onSearch="onSearch"></MemberPromotionsFilter>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
        <span slot="awardId" slot-scope="text, record, index">
          <span v-if="record.awardId">{{record.awardId}}</span>
          <span v-else>/</span>
        </span>
        
        <span slot="awardType" slot-scope="text, record, index">
          <!-- 奖品类型(1积分,2优惠券,3实物,0谢谢参与) -->
          <span v-if="record.awardType == 0">谢谢参与</span>
          <span v-if="record.awardType == 1">积分</span>
          <span v-if="record.awardType == 2">优惠券</span>
          <span v-if="record.awardType == 3">实物</span>
        </span>
        <span slot="image" slot-scope="text, record, index">
          <img class="img" :src="record.imageUrl" alt="" />
        </span>
        <span slot="address" slot-scope="text, record, index">
          <template v-if="record.awardType == 3">
            <template v-if="record.userName || record.userMobile || record.province || record.city || record.district || record.userAddress">
              <template v-if="record.userName">{{record.userName}},</template>
              <template v-if="record.userMobile">{{record.userMobile}},</template>
              <template v-if="record.province">{{record.province}},</template>
              <template v-if="record.city">{{record.city}},</template>
              <template v-if="record.district">{{record.district}},</template>
              <template v-if="record.userAddress">{{record.userAddress}}</template>
            </template>
            <template v-else>用户暂未完善收货信息</template>
            <a-icon type="form" style="margin-left: 10px;color: rgb(87, 87, 255);cursor: pointer;" @click="handleShowAddressModal(record)" />
          </template>
          <template v-else>/</template>
        </span>
        <span slot="giveState" slot-scope="text, record, index">
          <template v-if="record.giveState == 1 || record.awardType == 0">
            <div style="color: #09bb07;">已发放奖励</div>
            <template v-if="record.logisticsNo || record.logisticsCompany">（物流单号：{{ record.logisticsCompany || '' }}/{{ record.logisticsNo || '' }}）</template
            >
          </template>
          <template v-else>未发放奖励</template>
        </span>
        <span slot="action" slot-scope="text, record, index">
          <a v-if="record.giveState == 1 || record.awardType != 3" disabled>--</a>
          <a v-else @click="handleShowExpressModal(record)">发放奖励</a>
        </span>
      </s-table>
      <!-- 发放奖励 -->
      <a-modal title="发放奖励" :visible="expressVisible" width="500px" @ok="handleIssueGoods" @cancel="expressVisible = false">
        <a-form-model ref="expressRulesForm" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }" :model="expressForm" :rules="expressRules">
          <div>该用户为实物奖励，请联系顾客获取收货地址，安排奖品寄出后，再填写物流信息</div>
          <a-form-model-item label="物流公司" prop="logisticsCompany">
            <a-input v-model="expressForm.logisticsCompany" placeholder="请填写" />
          </a-form-model-item>
          <a-form-model-item label="物流单号" prop="logisticsNo">
            <a-input v-model="expressForm.logisticsNo" placeholder="请填写" />
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <!-- 修改收货信息 -->
      <a-modal title="修改收货信息" :visible="addressVisible" width="600px" @ok="handleSubmit" @cancel="addressVisible = false">
        <a-form-model ref="addressRulesForm" :model="addressForm" :rules="addressRules" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
          <a-form-model-item label="收货人姓名" prop="userName">
            <a-input v-model="addressForm.userName" placeholder="" />
          </a-form-model-item>
          <a-form-model-item label="收货人电话" prop="userMobile">
            <a-input v-model="addressForm.userMobile" placeholder="" />
          </a-form-model-item>
          <a-form-model-item label="收货地址" required>
            <a-row :gutter="5">
              <a-col :span="8">
                <a-form-model-item label="" style="width: 100%;" prop="provinceId">
                  <a-select v-model="addressForm.provinceId" @change="handleProvinceChange" show-search :filter-option="filterOption">
                    <a-select-option :value="province.id" v-for="province in provinceData" :key="province.id">
                      {{ province.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="" style="width: 100%;" prop="cityId">
                  <a-select v-model="addressForm.cityId" @change="handleCityChange" show-search :filter-option="filterOption">
                    <a-select-option :value="city.id" v-for="city in cityData" :key="city.id">
                      {{ city.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="" style="width: 100%;" prop="areaId">
                  <a-select v-model="addressForm.areaId" @change="handleDistrictChange" show-search :filter-option="filterOption">
                    <a-select-option :value="district.id" v-for="district in areaData" :key="district.id">
                      {{ district.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-form-model-item label="" style="width: 100%;" prop="userAddress">
              <a-textarea v-model="addressForm.userAddress" placeholder="" :auto-size="{ minRows: 3, maxRows: 5 }" />
            </a-form-model-item>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </div>
</template>
<script>

import MemberPromotionsFilter from '../../components/memberPromotionsFilter'
import { province, city, district, getLuckyDrawUserList, updateLuckyUserInfo, updateLogistics, exportLuckyDrawUserList } from '@/api/marketingCenter/luckyDraw.js'
import { STable } from '@/views/box/components'
import Header from '@/views/box/components/layouts/Header'
const columns = [
  {
    title: '序号',
    width: '100px',
    align: 'center',
    dataIndex: 'id'
  },
  {
    title: '用户手机号',
    width: '200px',
    align: 'center',
    dataIndex: 'mobile'
  },
  {
    title: '品牌卡号',
    width: '200px',
    align: 'center',
    dataIndex: 'cardNo'
  },
  {
    title: '归属店铺',
    width: '200px',
    align: 'center',
    dataIndex: 'storeName'
  },
  {
    title: '区部',
    width: '120px',
    align: 'center',
    dataIndex: 'areaName'
  },
  {
    title: '奖品类型',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'awardType' }
  },
  {
    title: '奖品名称',
    width: '120px',
    align: 'center',
    dataIndex: 'awardName'
  },
  {
    title: '奖品关联ID',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'awardId' }
  },
  {
    title: '奖品图',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'image' } 
  },
  {
    title: '收货信息',
    width: '200px',
    align: 'center',
    scopedSlots: { customRender: 'address' }
  },
  {
    title: '奖励发放状态',
    width: '200px',
    align: 'center',
    scopedSlots: { customRender: 'giveState' }
  },
  {
    title: '中奖时间',
    width: '200px',
    align: 'center',
    dataIndex: 'updateTime'
  },

  {
    title: '操作',
    width: '120px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    MemberPromotionsFilter,
    STable,
    Header
  },
  data() {
    return {
      columns,
      expressForm: {
      },
      expressRules: {
        logisticsCompany: [{ required: true, message: '请输入', trigger: 'blur' }],
        logisticsNo: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      addressForm: {
        provinceId: '',
        province: '',
        cityId: '',
        city: '',
        areaId: '',
        area: '',
        userName: '',
        userMobile: ''
      },
      addressRules: {
        provinceId: [{ required: true, message: '请选择', trigger: 'change' }],
        cityId: [{ required: true, message: '请选择', trigger: 'change' }],
        areaId: [{ required: true, message: '请选择', trigger: 'change' }],
        userName: [{ required: true, message: '请输入', trigger: 'blur' }],
        userAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
        userMobile: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const reg = /^(1)\d{10}$/
              if (!value && value !== 0) {
                callback()
              } else {
                if (reg.test(value)) {
                  callback()
                } else {
                  return callback(new Error('请输入正确的格式'))
                }
              }
            },
            trigger: 'blur'
          }
        ]
      },
      addressVisible: false,
      provinceData: [],
      cityData: [],
      areaData: [],
      total: 0,
      expressVisible: false,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const data = {
          luckyId: this.$route.params.id,
          "current": parameter.pageNo,
          "size": parameter.pageSize,
          ...this.queryParam
        }
        return getLuckyDrawUserList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            this.total = total
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
  },
  computed: {},
  mounted() {
  },
  watch: {},
  methods: {
    // 物流导入成功
    onImportLogistics() {
      this.$refs.table.refresh()
    },

    // 初始化省市区
    async initAddress(provinceId = '', cityId = '', areaId = '') {
      await this.getProvince(provinceId)
      await this.getCity(cityId)
      await this.getDistrict(areaId)
    },

    // 省change
    async handleProvinceChange(v) {
      this.cityData = []
      this.areaData = []
      this.addressForm.provinceId = v
      this.addressForm.province = this.provinceData.filter(e => e.id == v)[0].name
      this.addressForm.cityId = ''
      this.addressForm.city = ''
      this.addressForm.areaId = ''
      this.addressForm.area = ''
      await this.getCity()
      this.handleCityChange(this.addressForm.cityId)
    },

    // 市change
    async handleCityChange(v) {
      this.areaData = []
      this.addressForm.cityId = v
      this.addressForm.city = this.cityData.filter(e => e.id == v)[0].name
      this.addressForm.areaId = ''
      this.addressForm.area = ''
      await this.getDistrict()
    },

    // 区change
    async handleDistrictChange(v) {
      this.addressForm.areaId = v
      this.addressForm.area = this.areaData.filter(e => e.id == v)[0].name
    },

    // 获取省
    getProvince(provinceId) {
      return new Promise(resolve => {
        province().then(res => {
          if (res.code === 200) {
            this.provinceData = res.data
            this.addressForm.provinceId = provinceId ? provinceId : this.provinceData[0].id
            this.addressForm.province = provinceId ? this.provinceData.filter(e => e.id == provinceId)[0].name : this.provinceData[0].name
            resolve()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      })
    },

    // 获取市
    getCity(cityId, areaId) {
      if (!this.addressForm.provinceId) {
        return
      }
      const data = {
        provinceId: this.addressForm.provinceId
      }
      return new Promise(resolve => {
        city(data).then(res => {
          this.cityData = res.data
          this.addressForm.cityId = cityId ? cityId : this.cityData[0].id
          this.addressForm.city = cityId ? this.cityData.filter(e => e.id == cityId)[0].name : this.cityData[0].name
          resolve()
        })
      })
    },

    // 获取区
    getDistrict(areaId) {
      if (!this.addressForm.cityId) {
        return
      }
      const data = {
        cityId: this.addressForm.cityId
      }
      return new Promise(resolve => {
        district(data).then(res => {
          this.areaData = res.data
          this.addressForm.areaId = areaId ? areaId : this.areaData[0].id
          this.addressForm.area = areaId ? this.areaData.filter(e => e.id == areaId)[0].name : this.areaData[0].name
          resolve()
        })
      })
    },

    // 导出
    onExport() {
      if (this.total <= 0) {
        this.$message.error('暂无数据！')
        return
      }
      window.location.href = exportLuckyDrawUserList+`?luckyId=${this.$route.params.id}`
    },

    // 发放优惠券
    handleIssueCoupons(item) {
      const data = {
        ...item,
        status: 0
      }
      this.getTopicWinningUpdate(data)
    },
    
    // 显示物流输入框
    handleShowExpressModal(item) {
      const { id, province, city, district, userName, userMobile, userAddress} = item
      if (!province || !city || !district || !userName|| !userMobile|| !userAddress) {
        this.$message.error('用户暂未完善收货信息！')
        return
      }
      this.expressVisible = true
      this.expressForm = {
        id,
        logisticsCompany: '',
        logisticsNo: ''
      }
    },

    // 发放物品
    handleIssueGoods() {
      this.$refs.expressRulesForm.validate(valid => {
        if (valid) {
          this.expressVisible = false
          const data = {
            ...this.expressForm
          }
          updateLogistics(data).then(res => {
            if (res.code === 200) {
              this.$refs.table.refresh()
              this.expressForm = {}
            } else {
              this.$message.error(res.msg || res.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 修改地址
    handleShowAddressModal(item) {
      const {
        city,
        cityId,
        district,
        districtId,
        id,
        province,
        provinceId,
        userAddress,
        userMobile,
        userName
      } = item
      this.addressVisible = true
      this.addressForm = {
        city,
        cityId,
        area: district,
        areaId: districtId,
        id,
        province,
        provinceId,
        userAddress,
        userMobile,
        userName
      }
      this.initAddress(Number(provinceId), Number(cityId), Number(districtId))
    },

    // 确认修改地址
    handleSubmit() {
      this.$refs.addressRulesForm.validate(valid => {
        if (valid) {
          this.addressVisible = false
          const { areaId, area} =  this.addressForm
          const data = {
            ...this.addressForm,
            district: area,
            districtId: areaId
          }
          updateLuckyUserInfo(data).then(res => {
            if (res.code === 200) {
              this.$refs.table.refresh()
              this.addressForm = {}
            } else {
              this.$message.error(res.msg || res.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img-wrapper {
  display: flex;

  .img-list {
    display: flex;
  }

  .img-text {
    line-height: 60px;
    color: #999;
  }
}

.img {
  display: block;
  margin: 0 auto;
  width: 65px;
  height: 65px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.content {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
.content-btn {
  display: flex;
  justify-content: space-between;
  color: rgb(87, 87, 255);
  margin-right: 30px;
  cursor: pointer;
}
.product {
  display: flex;
  overflow: hidden;
  .img {
    margin: 0;
  }
  .product-name {
    flex: 1;
    margin-left: 5px;
    width: 80px;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
}
.product-list {
  .product-item {
    line-height: 18px;
    text-align: left;
  }

  .product-num {
    cursor: pointer;
    text-align: left;
  }
}
.content-record {
  position: absolute;
  right: 0;
  top: 15px;
}
.image-video-wrapper {
  position: relative;
  width: 60px;
  height: 60px;
  margin: 0 auto;
  .img-num {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    line-height: 18px;
    text-align: center;
    font-size: 12px;
    color: #fff;
    background: rgba(0, 0, 0, 0.5);
  }
}
</style>
